package spinning

import (
	"fmt"
	"net/http"
	"path"
	"time"

	"github.com/pkg/errors"
)

const (
	webUIDistDir          = "./web-ui/"
	getSpinningsPath      = "/edgex/api/getMachineStatus"
	getSpindleVoltagsPath = "/edgex/api/getSpindleVoltags"
)

func (app *SpinningApp) index(w http.ResponseWriter, req *http.Request) {
	url_path := path.Join(webUIDistDir, "index.html")
	app.lc.Info("### " + url_path + " ###")
	http.ServeFile(w, req, url_path)
}

func (app *SpinningApp) addRoutes() error {
	err := app.addRoute(getSpinningsPath, http.MethodGet, app.getSpinningsRoute)
	app.lc.Info("### " + getSpinningsPath + " ###")
	if err != nil {
		return err
	}

	_err := app.addRoute(getSpindleVoltagsPath, http.MethodGet, app.getSpindleVoltags)
	app.lc.Info("### " + getSpindleVoltagsPath + " ###")
	if _err != nil {
		return _err
	}

	app.fileServer = http.FileServer(http.Dir(webUIDistDir))
	// this is a bit of a hack to get refreshing working, as the path is /home
	err1 := app.addRoute("/home", http.MethodGet, app.index)
	app.lc.Info("### /home ###")
	if err1 != nil {
		return err1
	}

	// all other routes will be forwarded to serving the web-ui
	err2 := app.addRoute("/{path:.*}", http.MethodGet, app.serveWebUI)
	app.lc.Info("### /{path:.*} ###")
	if err2 != nil {
		return err2
	}

	return nil
}

func (app *SpinningApp) addRoute(path, method string, f http.HandlerFunc) error {
	if err := app.service.AddRoute(path, f, method); err != nil {
		return errors.Wrapf(err, "failed to add route, path=%s, method=%s", path, method)
	}
	return nil
}

func (app *SpinningApp) serveWebUI(w http.ResponseWriter, req *http.Request) {
	app.fileServer.ServeHTTP(w, req)
}

func (app *SpinningApp) getSpinningsRoute(w http.ResponseWriter, _ *http.Request) {
	indexResponse, err := app.getIndexResponse()

	fmt.Printf("%#v\n", indexResponse)
	//app.lc.Info()

	if err != nil {
		respondError(app.lc, w, http.StatusInternalServerError,
			fmt.Sprintf("Failed to get spinnings list: %v", err))
		return
	}

	respondJson(app.lc, w, indexResponse)
}

func (app *SpinningApp) getIndexResponse() (IndexResponse, error) {

	var indexResponse IndexResponse

	indexResponse.Realtime.Front_speed = 121
	indexResponse.Realtime.Status = 1
	indexResponse.Realtime.Spin_len = 23175
	indexResponse.Realtime.Theory_len = 28
	indexResponse.Realtime.Avg_speed = 10210
	indexResponse.Realtime.Progress = 74
	indexResponse.Realtime.Brokens = 8
	indexResponse.Realtime.Noocupations = 3
	indexResponse.Realtime.Weaks = 2
	indexResponse.Realtime.Malfunctions = 0
	indexResponse.Realtime.Passbys = 0
	indexResponse.Realtime.Ts = "2023-04-30 17:00"

	indexResponse.Settings.Name = "01"
	indexResponse.Settings.Standard_twist = 2
	indexResponse.Settings.Standard_front_speed = 2
	indexResponse.Settings.Spindle_mode = 1
	indexResponse.Settings.Spindle_count = 1008
	indexResponse.Settings.Plc_version = "4.11"
	indexResponse.Settings.Version = "V0.1"
	indexResponse.Settings.Boot_duration = 30
	indexResponse.Settings.Boot_delay = 30
	indexResponse.Settings.Roving_cut = 0

	indexResponse.Ts = fmt.Sprintf("%1d", time.Now().Unix())

	return indexResponse, nil
}
